using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using System.Reflection;
using EntityKit.Runtime;

namespace EntityKit.Editor
{
    public class EventSystemViewerWindow : EditorWindow
    {
        private Vector2 m_ScrollPosition;
        private bool m_ShowStatistics = true;
        private bool m_ShowListeners = true;
        private Dictionary<int, bool> m_ListenerFoldouts = new Dictionary<int, bool>();
        private Dictionary<string, bool> m_TypeFoldouts = new Dictionary<string, bool>();
        
        // 添加样式定义
        private GUIStyle m_HeaderStyle;
        private GUIStyle m_BoxStyle;
        private GUIStyle m_TitleStyle;
        private GUIStyle m_ButtonStyle;
        private GUIStyle m_SectionHeaderStyle;
        private GUIStyle m_LabelStyle;
        private GUIStyle m_ValueStyle;
        private GUIStyle m_FoldoutStyle;
        
        private const string FOLDOUT_OPEN_PREFIX = "▼ ";
        private const string FOLDOUT_CLOSED_PREFIX = "▶ ";
        
        public static void ShowWindow()
        {
            GetWindow<EventSystemViewerWindow>("事件系统查看器");
        }

        private void OnEnable()
        {
            minSize = new Vector2(400, 500);
        }
        
        private void InitStyles()
        {
            if (m_HeaderStyle == null)
            {
                m_HeaderStyle = new GUIStyle(EditorStyles.helpBox);
                m_HeaderStyle.fontSize = 14;
                m_HeaderStyle.fontStyle = FontStyle.Bold;
                m_HeaderStyle.alignment = TextAnchor.MiddleCenter;
                m_HeaderStyle.padding = new RectOffset(10, 10, 10, 10);
            }
            
            if (m_BoxStyle == null)
            {
                m_BoxStyle = new GUIStyle(EditorStyles.helpBox);
                m_BoxStyle.padding = new RectOffset(10, 10, 10, 10);
                m_BoxStyle.margin = new RectOffset(5, 5, 5, 5);
            }
            
            if (m_TitleStyle == null)
            {
                m_TitleStyle = new GUIStyle(EditorStyles.largeLabel);
                m_TitleStyle.fontSize = 18;
                m_TitleStyle.fontStyle = FontStyle.Bold;
                m_TitleStyle.alignment = TextAnchor.MiddleCenter;
                m_TitleStyle.normal.textColor = EditorGUIUtility.isProSkin ? new Color(0.8f, 0.8f, 0.8f) : new Color(0.2f, 0.2f, 0.2f);
            }
            
            if (m_ButtonStyle == null)
            {
                m_ButtonStyle = new GUIStyle(GUI.skin.button);
                m_ButtonStyle.padding = new RectOffset(10, 10, 10, 10);
            }
            
            if (m_SectionHeaderStyle == null)
            {
                m_SectionHeaderStyle = new GUIStyle(EditorStyles.boldLabel);
                m_SectionHeaderStyle.fontSize = 14;
                m_SectionHeaderStyle.margin = new RectOffset(0, 0, 5, 5);
                m_SectionHeaderStyle.normal.textColor = EditorGUIUtility.isProSkin ? new Color(0.7f, 0.85f, 1.0f) : new Color(0.1f, 0.3f, 0.6f);
            }
            
            if (m_LabelStyle == null)
            {
                m_LabelStyle = new GUIStyle(EditorStyles.label);
                m_LabelStyle.margin = new RectOffset(0, 0, 2, 2);
                m_LabelStyle.fontSize = 11;
            }
            
            if (m_ValueStyle == null)
            {
                m_ValueStyle = new GUIStyle(EditorStyles.label);
                m_ValueStyle.margin = new RectOffset(0, 0, 2, 2);
                m_ValueStyle.fontSize = 11;
                m_ValueStyle.normal.textColor = EditorGUIUtility.isProSkin ? new Color(0.7f, 0.9f, 0.7f) : new Color(0.1f, 0.5f, 0.1f);
            }
            
            if (m_FoldoutStyle == null)
            {
                m_FoldoutStyle = new GUIStyle(EditorStyles.foldout);
                m_FoldoutStyle.fontStyle = FontStyle.Bold;
                m_FoldoutStyle.fontSize = 12;
            }
        }

        private void OnGUI()
        {
            InitStyles();
            
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("事件系统查看器", m_TitleStyle);
            EditorGUILayout.Space();
            
            EditorGUILayout.BeginVertical(m_BoxStyle);
            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("🔄 刷新", m_ButtonStyle))
            {
                Repaint();
            }
            
            if (GUILayout.Button("🗑️ 清空所有事件", m_ButtonStyle))
            {
                if (EditorUtility.DisplayDialog("确认", "确定要清空所有事件吗？", "是", "否"))
                {
                    EventKit.ClearAll();
                    Repaint();
                }
            }
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndVertical();
            
            EditorGUILayout.Space();
            
            m_ScrollPosition = EditorGUILayout.BeginScrollView(m_ScrollPosition);
            
            // 显示统计信息
            m_ShowStatistics = EditorGUILayout.Foldout(m_ShowStatistics, 
                new GUIContent((m_ShowStatistics ? FOLDOUT_OPEN_PREFIX : FOLDOUT_CLOSED_PREFIX) + "📊 统计信息"), 
                true, m_FoldoutStyle);
            if (m_ShowStatistics)
            {
                EditorGUI.indentLevel++;
                DrawStatistics();
                EditorGUI.indentLevel--;
            }
            
            EditorGUILayout.Space();
            
            // 显示监听器信息
            m_ShowListeners = EditorGUILayout.Foldout(m_ShowListeners, 
                new GUIContent((m_ShowListeners ? FOLDOUT_OPEN_PREFIX : FOLDOUT_CLOSED_PREFIX) + "👂 事件监听器"), 
                true, m_FoldoutStyle);
            if (m_ShowListeners)
            {
                EditorGUI.indentLevel++;
                DrawEventListeners();
                EditorGUI.indentLevel--;
            }
            
            EditorGUILayout.EndScrollView();
        }
        
        private void DrawStatistics()
        {
            EditorGUILayout.BeginVertical(m_BoxStyle);
            EditorGUILayout.LabelField("系统状态", m_SectionHeaderStyle);
            
            // 通过反射获取事件系统内部状态
            var listenersField = typeof(EventKit).GetField("_listeners", BindingFlags.NonPublic | BindingFlags.Static);
            if (listenersField != null)
            {
                var listeners = listenersField.GetValue(null) as Dictionary<int, LinkedList<System.Action<IEventMessage>>>;
                if (listeners != null)
                {
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.LabelField("已注册事件类型数: ", m_LabelStyle);
                    EditorGUILayout.LabelField(listeners.Count.ToString(), m_ValueStyle);
                    EditorGUILayout.EndHorizontal();
                    
                    int totalListeners = 0;
                    foreach (var kvp in listeners)
                    {
                        if (kvp.Value != null)
                            totalListeners += kvp.Value.Count;
                    }
                    
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.LabelField("事件监听器总数: ", m_LabelStyle);
                    EditorGUILayout.LabelField(totalListeners.ToString(), m_ValueStyle);
                    EditorGUILayout.EndHorizontal();
                }
            }
            
            var postingListField = typeof(EventKit).GetField("_postingList", BindingFlags.NonPublic | BindingFlags.Static);
            if (postingListField != null)
            {
                var postingList = postingListField.GetValue(null) as List<object>;
                if (postingList != null)
                {
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.LabelField("待处理事件数: ", m_LabelStyle);
                    EditorGUILayout.LabelField(postingList.Count.ToString(), m_ValueStyle);
                    EditorGUILayout.EndHorizontal();
                }
            }
            
            EditorGUILayout.EndVertical();
            EditorGUILayout.Space();
        }
        
        private void DrawEventListeners()
        {
            EditorGUILayout.LabelField("活动监听器", m_SectionHeaderStyle);
            
            var listenersField = typeof(EventKit).GetField("_listeners", BindingFlags.NonPublic | BindingFlags.Static);
            if (listenersField != null)
            {
                var listeners = listenersField.GetValue(null) as Dictionary<int, LinkedList<System.Action<IEventMessage>>>;
                if (listeners != null && listeners.Count > 0)
                {
                    foreach (var kvp in listeners)
                    {
                        // 初始化折叠状态
                        if (!m_ListenerFoldouts.ContainsKey(kvp.Key))
                        {
                            m_ListenerFoldouts[kvp.Key] = false;
                        }
                        
                        EditorGUILayout.BeginVertical(EditorStyles.helpBox);
                        
                        m_ListenerFoldouts[kvp.Key] = EditorGUILayout.Foldout(
                            m_ListenerFoldouts[kvp.Key], 
                            new GUIContent((m_ListenerFoldouts[kvp.Key] ? FOLDOUT_OPEN_PREFIX : FOLDOUT_CLOSED_PREFIX) + 
                                         $"事件ID: {kvp.Key} ({kvp.Value?.Count ?? 0} 个监听器)"), 
                            true, m_FoldoutStyle);
                        
                        if (m_ListenerFoldouts[kvp.Key])
                        {
                            EditorGUI.indentLevel++;
                            
                            if (kvp.Value != null)
                            {
                                int listenerIndex = 1;
                                foreach (var listener in kvp.Value)
                                {
                                    if (listener != null)
                                    {
                                        // 创建一个可点击的GUI区域
                                        var rect = EditorGUILayout.GetControlRect();
                                        GUI.Label(rect, $"[{listenerIndex}] {listener.Target?.GetType().Name ?? "未知"}.{listener.Method?.Name ?? "未知"}", m_LabelStyle);
                                        
                                        // 检查是否点击了该区域
                                        if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition))
                                        {
                                            // 尝试选中对应的GameObject
                                            if (listener.Target is Component component && component != null && component.gameObject != null)
                                            {
                                                Selection.activeGameObject = component.gameObject;
                                                EditorGUIUtility.PingObject(component.gameObject);
                                            }
                                            else if (listener.Target is GameObject gameObject && gameObject != null)
                                            {
                                                Selection.activeGameObject = gameObject;
                                                EditorGUIUtility.PingObject(gameObject);
                                            }
                                            
                                            Event.current.Use();
                                        }
                                        
                                        listenerIndex++;
                                    }
                                }
                            }
                            
                            EditorGUI.indentLevel--;
                        }
                        
                        EditorGUILayout.EndVertical();
                    }
                }
                else
                {
                    EditorGUILayout.LabelField("暂无注册的监听器", EditorStyles.centeredGreyMiniLabel);
                }
            }
            
            EditorGUILayout.Space();
        }
    }
}